package com.echo.neocommunity.controller;


import com.echo.neocommunity.event.EventProducer;
import com.echo.neocommunity.pojo.Comment;
import com.echo.neocommunity.pojo.DiscussPost;
import com.echo.neocommunity.pojo.Event;
import com.echo.neocommunity.pojo.User;
import com.echo.neocommunity.service.impl.CommentServiceImpl;
import com.echo.neocommunity.service.impl.DiscussPostServiceImpl;
import com.echo.neocommunity.utils.CommunityConstant;
import com.echo.neocommunity.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.HtmlUtils;

import java.util.Date;

@Controller
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentServiceImpl commentService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private DiscussPostServiceImpl discussPostService;

    @Autowired
    private EventProducer producer;

    @PostMapping("/add/{discussPostId}")
    public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment){
        User user = hostHolder.getUser();
        if(comment.getEntityId()==0)
            comment.setEntityId(discussPostId);
        comment.setCreateTime(new Date());
        comment.setStatus(0);
        comment.setUserId(user.getId());
        DiscussPost discussPost = discussPostService.getById(discussPostId);
        commentService.addComment(comment,discussPost);
        Event event=new Event();
        event.setTopic(CommunityConstant.TOPIC_COMMENT);
        event.setUserId(user.getId());
        event.setEntityId(comment.getEntityId());
        event.setEntityType(comment.getEntityType());
        event.setData("postId",discussPostId);
        if(comment.getEntityType()==CommunityConstant.ENTITY_TYPE_POST){
            DiscussPost target = discussPostService.getById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }else if(comment.getEntityType()==CommunityConstant.ENTITY_TYPE_COMMENT){
            Comment target = commentService.getById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        producer.fireEvent(event);
        return "redirect:/discusspost/detail/"+discussPostId;
    }


}
